﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ft_module_parser
{
    class osages
    {
        public List<osage> opd = new List<osage>();
        public List<osage> opdft = new List<osage>();
        public List<osage> opdmerge = new List<osage>();

        public void Merge(string ac, string ft)
        {
            StreamReader srac = new StreamReader(ac);
            while (srac.Peek() > -1)
            {
                var line = srac.ReadLine();
                if (!line.Contains("length"))
                {
                    var lines = line.Split('.');
                    var id = int.Parse(lines[1]);
                    var key = lines[2].Split('=')[0];
                    var value = lines[2].Split('=')[1];

                    if (!opd.Any(c => c.id == id))
                    {
                        opd.Add(new osage(id));
                    }
                    var current = opd.Where(c => c.id == id).First();

                    if (key == "name")
                        current.name = value;

                    if (key == "ver")
                        current.ver = value;
                }
            }

            StreamReader srft = new StreamReader(ft);
            while (srft.Peek() > -1)
            {
                var line = srft.ReadLine();
                if (!line.Contains("length"))
                {
                    var lines = line.Split('.');
                    var id = int.Parse(lines[1]);
                    var key = lines[2].Split('=')[0];
                    var value = lines[2].Split('=')[1];

                    if (!opdft.Any(c => c.id == id))
                    {
                        opdft.Add(new osage(id));
                    }

                    var current = opdft.Where(c => c.id == id).First();

                    if (key == "name")
                        current.name = value;

                    if (key == "ver")
                        current.ver = value;
                }
            }

            int max = opd.Count;

            foreach (var i in opdft)
            {
                if (!opd.Any(c => c.name == i.name))
                {
                    i.id = max;
                    max++;
                    opd.Add(i);
                } else
                {
                    Console.WriteLine("DUPLICATE " + i.name);
                }
            }

            var sorted = opd.OrderBy(c => c.id.ToString());

            StreamWriter wr = new StreamWriter("merged_opd.txt");
            foreach (var i in sorted)
            {
                wr.WriteLine("file." + i.id + ".name=" + i.name);
                wr.WriteLine("file." + i.id + ".ver=" + i.ver);
            }
            wr.WriteLine("file.length=" + opd.Count);
            wr.Close();
        }

    }
}
